package pl.edu.pw.ee.buildcity.servlets.rss;

import com.sun.syndication.io.FeedException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import pl.edu.pw.ee.buildcity.notifiers.RSSFeedPublisher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mateusz
 * @since 2010-03-14
 */
public class BuildCityRSS extends HttpServlet {

	private RSSFeedPublisher rssPublisher;

	@Override
	public void init() throws ServletException {
		super.init();
		WebApplicationContext springContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		rssPublisher = (RSSFeedPublisher) springContext.getBean("rssPublisher");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		try {
			String buildDef = request.getParameter("buildDef");
			out.write(rssPublisher.publish(buildDef));
		} catch (FeedException e) {
			e.printStackTrace();
			throw new ServletException("Could not generate feed", e);
		}
	}
}
